var express = require("express");
var router = express.Router();
var fs = require("fs");
const Result = require("../utils/result");
const multer = require("multer");
const upload = multer({ dest: "public/images/post/" }); // 文件储存路径
const postService = require("../services/postServices");
const commentService = require("../services/commentService");
const likeService = require("../services/likeService");

//发表文章
router.post("/add", async function (req, res) {
  const { content, imgs, userId, place } = req.body;
  await postService.add(content, imgs, userId, place);
  res.json(Result.success());
});

// 上传图片
router.post("/uploadImg", upload.single("file"), function (req, res, next) {
  try {
    let file = req.file;
    const oldPath = file.destination + file.filename;
    console.log(oldPath);
    const type = file.mimetype.split("/")[1];
    const fileFullname = file.filename + "." + type;
    const newPath = "public/images/post/" + fileFullname;
    console.log(newPath);
    // 修改文件名，为文件加上后缀
    fs.rename(oldPath, newPath, function (err) {
      if (err) {
        throw err;
      }
    });
    // 返回静态资源地址
    const imageUrl = "http://localhost:8080/images/post/" + fileFullname;
    res.json(Result.success({ imageUrl }));
  } catch (err) {
    res.json(Result.fail(err));
  }
});

router.get("/list", async function (req, res) {
  const { size, page, college, userId } = req.query;
  const { rows, count } = await postService.getPostList(
    college,
    size,
    page,
    userId
  );
  res.json(Result.success({ postArr: rows, count }));
});

//获取文章详情
router.get("/detail", async function (req, res) {
  const { postId, size, page, userId } = req.query;
  const post = await postService.getOnePost(postId, userId);
  const { rows, count } = await commentService.getList(postId, size, page);
  res.json(Result.success({ post, comments: rows, count }));
});

//点赞文章
router.get("/like", async function (req, res) {
  const { authorId, userId, postId } = req.query;
  await likeService.like(authorId, userId, postId);
  res.json(Result.success());
});

//取消点赞文章
router.get("/dislike", async function (req, res) {
  const { authorId, userId, postId } = req.query;
  await likeService.dislike(authorId, userId, postId);
  res.json(Result.success());
});

//删除文章
router.get("/delete", async function (req, res) {
  const { postId, userId } = req.query;
  await postService.delete(postId, userId);
  res.json(Result.success());
});

//获取某个人的动态文章列表
router.get("/dynamicList", async function (req, res) {
  const { userId, size, page } = req.query;
  const { dynamicArr } = await postService.getAllDynamic(userId, size, page);
  res.json(Result.success({ dynamicArr }));
});

module.exports = router;
